Skip to content

LinkedSelectionModel

Base classes

Name Children Inherits
ItemSelectionModel
prettyqt.core.itemselectionmodel
Keeps track of a view's selected items.

⋔ Inheritance diagram

graph TD
  3649776053["itemmodels.LinkedSelectionModel"]
  3482886083["core.ItemSelectionModel"]
  3227531497["core.ObjectMixin"]
  2751680898["builtins.object"]
  3396490578["QtCore.QItemSelectionModel"]
  3984060476["QtCore.QObject"]
  37984305["Shiboken.Object"]
  3482886083 --> 3649776053
  3227531497 --> 3482886083
  2751680898 --> 3227531497
  3396490578 --> 3482886083
  3984060476 --> 3396490578
  37984305 --> 3984060476
  2751680898 --> 37984305

🛈 DocStrings

Bases: ItemSelectionModel

An ItemSelectionModel which link selections between item models.

Source code in prettyqt/itemmodels/proxies/linkedselectionmodel.py
class LinkedSelectionModel(core.ItemSelectionModel):
    """An ItemSelectionModel which link selections between item models."""

    # TODO: atm this doesnt need to inherit from ItemSelectionModel.
    # Not sure if there is any advantage in doing so...
    # Otherwise we could rename to SelectionLinker and just inherit from
    # object / core.Object
    def __init__(
        self,
        *itemviews,
        **kwargs,
    ):
        super().__init__(**kwargs)
        self._itemviews = itemviews
        self._models = [w.model() for w in itemviews]
        self._mapper = itemmodels.ProxyMapper(*self._models)
        for w in itemviews:
            w.selectionModel().currentChanged.connect(self._on_current_change)
            w.selectionModel().selectionChanged.connect(self._on_selection_change)

    def _on_current_change(self, new: core.ModelIndex, _):
        if not isinstance(sender := self.sender(), core.QItemSelectionModel):
            return
        source = sender.model()
        source_index = self._models.index(source)
        target_indexes = list(range(len(self._models)))
        target_indexes.remove(source_index)
        for target_index in target_indexes:
            mapped = self._mapper.map_index(
                source=source_index, target=target_index, index=new
            )
            self._itemviews[target_index].setCurrentIndex(mapped)

    def _on_selection_change(self, new: core.QItemSelection, _):
        if not isinstance(sender := self.sender(), core.QItemSelectionModel):
            return
        source_model = sender.model()
        source_index = self._models.index(source_model)
        target_indexes = list(range(len(self._models)))
        target_indexes.remove(source_index)
        for target_index in target_indexes:
            selected = self._mapper.map_selection(
                source=source_index, target=target_index, selection=new
            )
            sel_model = self._itemviews[target_index].selectionModel()
            sel_model.select(selected, sel_model.SelectionFlag.Select)

:fa-brands-github: Show source on GitHub